package com.dure.hotmemory.controllers;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;

import com.dure.commonlib.util.AssetsUtil;
import com.dure.commonlib.util.DbUtils;
import com.dure.commonlib.util.PreferencesUtils;
import com.dure.commonlib.util.StreamUtil;
import com.dure.hotmemory.R;
import com.dure.hotmemory.adapters.CodeDetailAdapter;
import com.dure.hotmemory.bean.Bean;
import com.dure.hotmemory.bean.Code;
import com.dure.hotmemory.bean.CodeDao;
import com.dure.hotmemory.bean.Level;
import com.dure.hotmemory.bean.LevelBase;
import com.dure.hotmemory.bean.Planet;
import com.dure.hotmemory.bean.Record;
import com.dure.hotmemory.config.Config;
import com.dure.hotmemory.listeners.ConfirmListener;
import com.dure.hotmemory.listeners.TopChangeListener;
import com.dure.hotmemory.scenes.BaseScene;
import com.dure.hotmemory.scenes.TrainingInfoScene;
import com.dure.hotmemory.utils.DialogUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.socks.library.KLog;

import org.greenrobot.greendao.query.WhereCondition;
import org.xutils.db.sqlite.WhereBuilder;

import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

/**
 * Created by leix on 10/06/2017.
 */

public class TrainingInfoController extends Controller {
    TrainingInfoScene trainingInfoScene;
    Dialog dialog;
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
           switch (msg.what){
               case 0:
                   if (dialog != null){
                       dialog.dismiss();
                   }
                   List<Code> codeList = (List<Code>) msg.obj;
                   trainingInfoScene.setCodeList(codeList);
                   break;
           }
        }
    };
    public TrainingInfoController(TrainingInfoScene baseScene) {
        super(baseScene);
        trainingInfoScene = baseScene;
    }

    @Override
    public void handleRequestSuccess(Bean bean) {
        if (bean instanceof LevelBase) {
            LevelBase levelBase = (LevelBase) bean;
            trainingInfoScene.setAdapterData(levelBase.data);
        }if (bean instanceof Record) {
            Record record = (Record) bean;
            Level level = null;
            if (record.status == 1){
                level = record.data.get(0);
            }
            trainingInfoScene.setTrainingData(level);

        }
    }

    public void showCodeDetailDialog(final Code code, final ConfirmListener confirmListener) {
        final Dialog dialog = new Dialog(activity, R.style.customDialog);
        View view = LayoutInflater.from(activity).inflate(R.layout.code_detail_dialog, null);
        TextView titleTV = (TextView) view.findViewById(R.id.title_tv);
        TextView closeTV = (TextView) view.findViewById(R.id.close_tv);
        TextView editTV = (TextView) view.findViewById(R.id.edit_tv);
        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);

        titleTV.setText("编码：" + code.number);

        closeTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();
                if (confirmListener != null) {
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("isClose", true);
                    confirmListener.confirmed(bundle);
                }
            }
        });

        editTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.cancel();
                if (confirmListener != null) {
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("isClose", false);
                    confirmListener.confirmed(bundle);
                }
            }
        });

//        addCodeDetailItem(code, contentLL);

        CodeDetailAdapter adapter = new CodeDetailAdapter(activity);
        recyclerView.setLayoutManager(new LinearLayoutManager(activity));
        recyclerView.setAdapter(adapter = new CodeDetailAdapter(activity));
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect,
                                       View view,
                                       RecyclerView parent,
                                       RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.left = 10;
                outRect.top = 10;
                outRect.right = 10;
                outRect.bottom = 20;
            }
        });

        CodeDao codeDao = activity.daoSession.getCodeDao();

//        long count = codeDao.queryBuilder().where(CodeDao.Properties.Number.eq(code.number),CodeDao.Properties.Type.eq(code.type)).count();
//        if (count == 0){
//            code.position = 0;
//            codeDao.insert(code);
//        }

        List<Code> codeList = codeDao.queryBuilder()
                .where(CodeDao.Properties.Number.eq(code.number),CodeDao.Properties.Type.eq(code.type))
                .orderAsc(CodeDao.Properties.Position)
                .list();
        adapter.setCodeList(codeList);
        adapter.setTopChangeListener(new TopChangeListener() {
            @Override
            public void onTopChanged(Code topCode) {
//                code.name = topCode.name;
//                code.image = topCode.image;
//                code.isCreated = topCode.isCreated;
//                code.position = topCode.position;
            }
        });

        dialog.setCanceledOnTouchOutside(false);
        WindowManager windowManager = activity.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        int width = (int) (display.getWidth() * 0.8f);

        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.setContentView(view, params);

        dialog.show();
    }

    public List<Code> getCodeListFromDB(Code code) {
        // fake data
        ArrayList<Code> codeArrayList = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            Code codeItem = new Code();
            codeItem.name = code.name + i;
            codeItem.number = code.number;
            codeItem.image = code.image;
            codeArrayList.add(codeItem);
        }
//        codeArrayList.add(code);
//        codeArrayList.add(code);

        return codeArrayList;
    }

    public void loadCodeList(final Planet planet) {
        final CodeDao codeDao = activity.daoSession.getCodeDao();
//
//        final List<Code> codeList = codeDao.queryBuilder()
//                .where(CodeDao.Properties.Type.eq(planet.alias), CodeDao.Properties.Position.eq(0))
//                .orderAsc(CodeDao.Properties.Index)
//                .list();

//        if (codeList.size() == 0){
            KLog.d("lesleixz", "first get");
//            PreferencesUtils.getBoolean(activity, planet.alias + ":data_loaded", true);
            dialog = DialogUtil.showLoadingDialog(activity, "数据加载中， 请稍候...");
            activity.executorService.execute(new Runnable() {
                @Override
                public void run() {
                    InputStream is = AssetsUtil.getAssets(activity, planet.assets);
                    Gson gson = new Gson();
                    String codeJsonStr = StreamUtil.inputStream2String(is);
                    Type datasetListType = new TypeToken<Collection<Code>>() {}.getType();
                    final List<Code>  codeArrayList = gson.fromJson(codeJsonStr, datasetListType);
//                    codeList.addAll(codeArrayList);


                    for (int i = 0; i < codeArrayList.size(); i++) {// 将数据放入数据库
                        Code code = codeArrayList.get(i);
                        code.position = 0;
                        code.index = i;
                        code.type = planet.alias;
                        codeDao.insert(code);
                    }
                    Message message = handler.obtainMessage();
                    message.obj = codeArrayList;
                    message.what = 0;
                    message.sendToTarget();

                }
            });

//
//            dialog.dismiss();
//        }


//        return codeList;
    }

    public void getTop(String trainingName) {
        HashMap<String, String> paramMap = new HashMap<>();

        paramMap.put("training_name", trainingName);

        requestModel.doPost(Config.HOST + Config.GET_TOP_10, paramMap, LevelBase.class);
    }

    public void getTrainingData(String trainingName){
        HashMap<String, String> paramMap = new HashMap<>();
        if (!TextUtils.isEmpty(PreferencesUtils.getString(activity, "phone")))
            paramMap.put("phone", PreferencesUtils.getString(activity, "phone"));
        else if (!TextUtils.isEmpty(PreferencesUtils.getString(activity, "uid")))
            paramMap.put("uid", PreferencesUtils.getString(activity, "uid"));
        paramMap.put("training_name", trainingName);

        requestModel.doPost(Config.HOST + Config.GET_LEVEL, paramMap, Record.class);
    }
}
